package cn.afterturn.oneopen.filter;

import cn.afterturn.oneopen.model.OperationLogModel;
import cn.afterturn.oneopen.service.IOperationLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 访问时长拦截器
 *
 * @author by jueyue on 19-3-9.
 */
@Component
public class RequestTimeFilter implements GlobalFilter, Ordered {

    private static final Logger log                = LoggerFactory.getLogger(GatewayFilter.class);
    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";

    private IOperationLogService operationLogService;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().get("token").get(0);
        exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if (startTime != null) {
                        long              time = (System.currentTimeMillis() - startTime);
                        OperationLogModel log  = new OperationLogModel();
                        log.setCrtTime(new Date());
                        log.setUrl(exchange.getRequest().getPath().pathWithinApplication().value());
                        log.setAccountNo(token);
                        log.setTimes((int) time);
                        redisTemplate.opsForList().leftPush("TIME:LOG", log);
                    }
                })
        );

    }

    @Override
    public int getOrder() {
        return 2;
    }
}
